class Compiler {
  constructor(vm) {
    this.vm = vm
    this.el = vm.$el
    this.compile(this.el)
  }
  compile (el) {
    const childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if (this.isTextNode(node)) this.compileText(node)
      if (this.isElementNode(node)) this.compileElement(node)
      // 判断node节点，是否有子节点，如果有子节点，要递归调用compile
      if (node.childNodes && node.childNodes.length) this.compile(node)
    })
  }
  // 处理文本节点 - 差值表达式 - {{ msg }}
  compileText (node) {
    // console.log(node, 15)
    const reg = /\{\{(.+?)\}\}/ // 源码中: /\{\{((?:.|\r?\n)+?)\}\}/g
    const value = node.textContent
    if (reg.test(value)) {
      const key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])
      new Watcher(this.vm, key, newValue => {
        node.textContent = value.replace(reg, newValue)
      })
    }
  }
  // 处理元素节点 - 'v-'
  compileElement (node) {
    // console.log(node, 18)
    // 遍历属性节点
    Array.from(node.attributes).forEach(attr => {
      console.dir(attr.name)
      let attrName = attr.name
      if (this.isDirective(attrName)) {  // v-text  v-model
        const key = attr.value
        attrName = attrName.slice(2)
        this.update(attrName, key, node)
      }
    })
  }
  update (attrName, key, node) {
    const updateFn = this[attrName + 'Update']
    updateFn && updateFn.call(this, node, key)
  }
  textUpdate (node, key) { //  v-text="msg"
    node.textContent = this.vm[key]
    new Watcher(this.vm, key, newValue => {
      node.textContent = newValue
    })
  }
  modelUpdate (node, key) {  // v-model="msg"
    node.value = this.vm[key]
    new Watcher(this.vm, key, newValue => {
      node.value = newValue
    })

    node.addEventListener('input', () => {
      console.log(60);
      this.vm[key] = node.value
    })
  }
  // 判断元素属性是否是指令
  isDirective (attrName) {
    return attrName.startsWith('v-')
  }
  // 判断节点是否是文本节点
  isTextNode (node) {
    return node.nodeType === 3
  }
  // 判断节点是否是元素节点
  isElementNode (node) {
    return node.nodeType === 1
  }
}